package cn.billho.popcache.core.codec;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


public class JSONSerialize implements ISerialize {
    @Override
    public <T> T deserialize(String val, Class<T> clz) {
        return JSON.parseObject(val, clz);
    }

    @Override
    public Object deserialize(String value, Type returnType, Class<?>... origins) {
        Object result = null;
        if (returnType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) returnType;
            Type rawType = parameterizedType.getRawType();
            if (((Class) rawType).isAssignableFrom(List.class)) {
//                result = JSON.parseArray(value, (Class) parameterizedType.getActualTypeArguments()[0]);
                //fix 多层泛型引起的bug
                if (parameterizedType.getActualTypeArguments()[0] instanceof ParameterizedType) {
                    if(JSONObject.class.equals(((ParameterizedType)(parameterizedType.getActualTypeArguments()[0])).getActualTypeArguments()[0])){
                        result = JSON.parseArray(value,(Class)((ParameterizedType)(parameterizedType.getActualTypeArguments()[0])).getRawType());
                    }
                    else {
                        result = JSON.parseArray(value, parameterizedType.getActualTypeArguments());
                    }
                }
                else {
                    result = JSON.parseArray(value, (Class) parameterizedType.getActualTypeArguments()[0]);
                }
            }
            else {
                result = JSON.parseObject(value, returnType);
            }
        } else if (origins == null) {
            result = JSON.parseObject(value, returnType);
        } else {
            result = JSON.parseObject(value, origins[0]);
        }
        return result;
    }

    @Override
    public String serialize(Object val) {
        if (val instanceof String){
            return val.toString();
        }
        return JSON.toJSONString(val);
    }

}
